package com.qeng.aiwanba.util;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qeng.aiwanba.R;
import com.qeng.aiwanba.net.URLLoader;
import com.qeng.aiwanba.view.CircleProgressView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * Created by lixy on 2017/4/14.
 */

public class VersionTools {
    public static void checkVersion(final Context context, final boolean showToast){
        try {
            new URLLoader("http://api.aiwanba.com/android/aiwanba.txt", new URLLoader.Listener() {
                @Override
                public void success(String url) {
                    if(url != null && !url.equals("")){
                        try {
                            JSONObject json;
                            json = new JSONObject(url);
                                String newVersion = json.getString("versionName");
                                int versionCode = json.getInt("versionCode");
                                final String apkurl = json.getString("url");
                                String desc = json.getString("desc");
                                if(Util.getVersionCode(context) < versionCode){

                                    showUpdateDialog(context,desc,newVersion,apkurl);

                                }else if(showToast){
                                    Util.showToast(context, context.getString(R.string.alredy_new_version));
                                }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void fail() {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void showUpdateDialog(final Context context, String update_desc, final String versionName, final String apkUrl){
        final Dialog dialog = new Dialog(context,R.style.Translucent_NoTitle);

        View view = LayoutInflater.from(context).inflate(R.layout.dialog_update,null);
        final LinearLayout desc_ll = (LinearLayout)view.findViewById(R.id.update_desc_ll);
        final RelativeLayout progress_rl = (RelativeLayout)view.findViewById(R.id.update_progress_rl);
        TextView desc_tv = (TextView)view.findViewById(R.id.version_desc_tv);
        final CircleProgressView progressView = (CircleProgressView)view.findViewById(R.id.circleProgressbar);

        desc_tv.setText(update_desc);

        view.findViewById(R.id.start_update_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                desc_ll.setVisibility(View.INVISIBLE);
                progress_rl.setVisibility(View.VISIBLE);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        downloadApk(context,dialog,apkUrl,versionName,progressView);
                    }
                }).start();
            }
        });
        view.findViewById(R.id.dialog_close_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.setContentView(view);
        dialog.show();
    }

    private static void downloadApk(final Context context, Dialog dialog, String apkUrl, String versionName, final CircleProgressView pd){
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            URL url = null;
            try {
                url = new URL(apkUrl);
                HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                final int max = conn.getContentLength();
                pd.setMaxProgress(100);
                if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    InputStream is = conn.getInputStream();
                    File file = new File(Environment.getExternalStorageDirectory(), "爱玩吧_" + versionName + ".apk");
                    FileOutputStream fos = new FileOutputStream(file);
                    BufferedInputStream bis = new BufferedInputStream(is);
                    byte[] buffer = new byte[1024];
                    int len;
                    int total = 0;
                    while ((len = bis.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                        total += len;
                        final int progress = (int) (total * 100 / conn.getContentLength());
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //获取当前下载量
                                pd.setProgress(progress);
                            }
                        });
                    }
                    fos.close();
                    bis.close();
                    is.close();
                    Util.installApk(context, file);
                }else{
                    ((Activity)context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Util.showToast(context,context.getString(R.string.tip_download_apk_failed));
                        }
                    });
                }
                dialog.dismiss();
                return ;
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        return;
    }

}
